import React, { useContext, useEffect, useRef, useState } from "react";
import {
  View,
  StyleSheet,
  Text,
  TouchableOpacity,
  Alert,
  TextInput,
} from "react-native";
import { Entypo } from "@expo/vector-icons";
import { AntDesign } from "@expo/vector-icons";
import Dropdown from "./dropdown";
import MaterialContext from "../context/suppiler/materialContext";
import ComMaterialContext from "../context/suppiler/comMaterialContext";
import GoodsContext from "../context/suppiler/goodsContext";
import LoadingBar from "./LoadingBar";
import ScrollPicker from "./ScrollPicker";

const materialCard = (props) => {
  const processOptions = (arr) => {
    let options = [];
    arr.map((item) => {
      options.push(item.type);
    });
    return options;
  };

  const { material } = useContext(MaterialContext);
  const { editComMaterial, deleteComMaterial } = useContext(ComMaterialContext);
  const { regetGoods } = useContext(GoodsContext);
  let item = props.item;
  // console.log("材料", item);

  const [isVisible, setIsvisible] = useState(false); //详细信息
  const [selected, setSelected] = useState(false); //批量删除
  const [isEditable, setIsEditable] = useState(false); //编辑
  const [isLoading, setIsLoading] = useState(false);

  const costType = ["按面积", "按重量"]; //0按面积计算 1 按重量计算
  const Allcategories = [];
  const categories = material.map((item) => {
    Allcategories.push(item.category);
    return item.category;
  });
  const AllTypes = [];

  let categoryIndex = (categories || []).findIndex((i) => i === item.category);

  let typeIndex = (material[categoryIndex].types || []).findIndex(
    (i) => i.type === item.type
  );

  material.map((item, index) => {
    let t_material = processOptions(item.types);
    t_material.unshift("");
    t_material.push("");
    AllTypes.push(t_material);
  });
  Allcategories.unshift("");
  Allcategories.push("");

  const [category, setCategory] = useState(categoryIndex);
  const [type, setType] = useState(typeIndex);
  const [cost, setCost] = useState(item.m_cost.toString());
  const [editCalType, setEditCalType] = useState(item.processMode); //编辑时计价方式的修改

  useEffect(() => {
    setCategory(categoryIndex);
    setType(typeIndex);
  }, [categoryIndex, typeIndex]);

  const confirmDelete = (id) => {
    Alert.alert("提示", "确定要删除该材料吗?\n(*注意:该操作将删除相关的商品)", [
      {
        text: "取消",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          setIsLoading(true);
          deleteComMaterial(
            id,
            () => {
              setIsLoading(false);
            },
            () => {
              regetGoods();
            }
          );
          // setIsvisible(false);
        },
      },
    ]);
  };

  const cancelEdit = () => {
    setCategory(categoryIndex);
    setType(typeIndex);
    setCost(item.m_cost.toString());
    setEditCalType(item.processMode);
  };

  const confirmSave = () => {
    Alert.alert("提示", "确定保存已做修改吗?\n(*注意:该操作将修改相关的商品)", [
      {
        text: "取消",
        onPress: () => {
          console.log("Cancel Pressed");
          cancelEdit();
        },
        style: "cancel",
      },
      {
        text: "确定",
        onPress: () => {
          if (cost == "" || cost == 0) {
            Alert.alert("提示", "原料费不能为空", [{ text: "确定" }]);
            return;
          }
          setIsLoading(true);
          let data = {
            category: categories[category],
            type: material[category].types[type].type,
            density: item.density,
            m_cost: cost,
            processMode: editCalType,
            _id: item._id,
            company_id: item.company_id,
          };
          // console.log("保存的item是---", data);
          editComMaterial(
            data,
            () => {
              setIsLoading(false);
            },
            () => {
              regetGoods();
            }
          );
          setIsEditable(false);
        },
      },
    ]);
  };

  const normalCard = () => {
    return (
      <View style={styles.detail}>
        <LoadingBar visible={isLoading} />
        <View style={{ flexDirection: "row", justifyContent: "flex-end" }}>
          <TouchableOpacity
            style={{ marginRight: 15 }}
            onPress={() => {
              setIsEditable(true);
            }}
          >
            <AntDesign name="edit" size={15} color="#6495ed" />
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => {
              confirmDelete(item._id);
            }}
          >
            <AntDesign name="delete" size={15} color="orange" />
          </TouchableOpacity>
        </View>

        <View style={styles.detailItem}>
          <Text style={styles.detailText}>
            材料: {item.category + item.type}
          </Text>
        </View>
        {/* <View style={styles.detailItem}>
          <Text style={styles.detailText}>型号: {item.type}</Text>
        </View> */}
        <View style={styles.detailItem}>
          <Text style={styles.detailText}>密度: {item.density} g/m³</Text>
        </View>

        <View style={styles.detailItem}>
          <Text style={styles.detailText}>原料费: {item.m_cost}</Text>
          {item.processMode === "1" ? (
            <Text style={styles.detailText}> 元/kg </Text>
          ) : (
            <Text style={styles.detailText}> 元/㎡ </Text>
          )}
        </View>
      </View>
    );
  };

  const EditableCard = () => {
    return (
      <View style={styles.detail}>
        <View
          style={{
            flexDirection: "row",
            justifyContent: "flex-end",
            marginBottom: 5,
          }}
        >
          <TouchableOpacity
            style={{ marginRight: 15 }}
            onPress={() => {
              setIsEditable(false);
              cancelEdit();
            }}
          >
            <AntDesign name="closecircleo" size={17} color="#6495ed" />
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => {
              confirmSave();
            }}
          >
            <AntDesign name="checkcircleo" size={17} color="orange" />
          </TouchableOpacity>
        </View>

        <View style={styles.editItem}>
          <Text style={styles.detailText}>材料: </Text>
          <View style={styles.inputView}>
            <ScrollPicker
              options={[Allcategories, AllTypes]}
              selectedIndex={[category, type]}
              onSubmit={(index1, category, index2, type) => {
                setCategory(index1);
                // realCategory.current = value;
                setType(index2);
                // if (index1 !== item.category) {
                //   setType(0); //避免A商品有4个 B商品有2个 但初始值是4的局面
                // }
              }}
            ></ScrollPicker>
          </View>
          {/* <Dropdown
            ifFirst={1}
            initialValues={{
              initKey: category,
              initOptions: categories,
            }}
            initialStyles={{
              valueWith: 217,
              valueMarginTop: 0,
              optionsWidth: 110,
              optionsBackGroundColor: "#eee",
              optionsBorderColor: "#ccc",
            }}
            onSelect={(itemm, value) => {
              setCategory(value);
              // realCategory.current = value;
              if (value !== item.category) {
                setType(0); //避免A商品有4个 B商品有2个 但初始值是4的局面
              }
            }}
          /> */}
        </View>
        {/* <View style={styles.editItem}>
          <Text style={styles.detailText}>型号: </Text>

          <Dropdown
            ifFirst={1}
            initialValues={{
              initKey: type,
              initOptions: material[category].types.map((item) => {
                return item.type;
              }),
            }}
            initialStyles={{
              valueWith: 217,
              valueMarginTop: 0,
              optionsWidth: 110,
              optionsBackGroundColor: "#eee",
              optionsBorderColor: "#ccc",
            }}
            onSelect={(itemm, value) => {
              setType(value);
            }}
          />
        </View> */}
        <View style={styles.editItem}>
          <Text style={styles.detailText}>密度: </Text>
          <Text style={styles.detailText}>{item.density}</Text>
          <Text style={styles.detailText}>g/m³ </Text>
        </View>
        <View style={styles.editItem}>
          <Text style={styles.detailText}>加工方式: </Text>
          {costType.map((tag, index) => {
            return (
              <TouchableOpacity
                key={index}
                onPress={() => {
                  setEditCalType(index.toString());
                }}
              >
                <Text
                  key={index}
                  style={
                    index.toString() === editCalType
                      ? styles.selectedTag
                      : styles.tag
                  }
                >
                  {tag}
                </Text>
              </TouchableOpacity>
            );
          })}
        </View>
        <View style={styles.editItem}>
          <Text style={styles.detailText}>原料费: </Text>
          <TextInput
            style={{
              marginLeft: 10,
              backgroundColor: "#F3F3F3",
              borderRadius: 5,
              flex: 1,
              marginRight: 10,
            }}
            value={cost}
            keyboardType="numeric"
            onChangeText={(cost) => {
              setCost(cost);
              item.cost = cost;
            }}
            placeholder="请输入原料费"
            textAlign="center"
          />
          {editCalType === "1" ? (
            <Text style={styles.detailText}> 元/kg </Text>
          ) : (
            <Text style={styles.detailText}> 元/㎡ </Text>
          )}
        </View>
      </View>
    );
  };

  return (
    <View>
      <View style={styles.container}>
        {props.isMutilDelete && (
          <TouchableOpacity
            style={styles.delete}
            onPress={() => {
              let i = !selected;
              setSelected(i);
              if (i) {
                props.onPressSelect(props.index, 0);
              } else {
                props.onPressSelect(props.index, 1);
              }
            }}
          >
            {selected ? (
              <AntDesign name="checkcircleo" size={15} color="#67c23a" />
            ) : (
              <Entypo name="circle" size={15} color="#D8D8D8" />
            )}
          </TouchableOpacity>
        )}
        <TouchableOpacity
          style={styles.card}
          onPress={() => setIsvisible(!isVisible)}
        >
          <AntDesign name="isv" size={20} color="orange" />
          <Text style={styles.text}>
            {item.category}
            {item.type}
          </Text>
          <Text style={styles.text}>
            {item.m_cost}
            {item.processMode === "1" ? (
              <Text style={styles.detailText}> 元/kg </Text>
            ) : (
              <Text style={styles.detailText}> 元/㎡ </Text>
            )}
          </Text>
          {isVisible ? (
            <Entypo name="chevron-small-down" size={20} color="#555" />
          ) : (
            <Entypo name="chevron-small-right" size={20} color="#555" />
          )}
        </TouchableOpacity>
      </View>

      {isVisible && !isEditable && normalCard(item)}
      {isEditable && EditableCard(item)}
    </View>
  );
};

const styles = StyleSheet.create({
  card: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    backgroundColor: "#fff",
    marginRight: 15,
    marginLeft: 15,
    padding: 13,
    paddingLeft: 10,
    borderRadius: 5,
    marginBottom: 10,
    elevation: 4, //设置阴影角度，通过这个设置有无阴影
    shadowOffset: {
      // 设置阴影偏移量
      width: 0,
      height: 4,
    },
    shadowRadius: 4, // 设置阴影模糊半径
    shadowOpacity: 0.1, // 设置阴影的不透明度
    shadowColor: "gray", // 设置阴影色
    flex: 9,
  },
  container: {
    flexDirection: "row",
    justifyContent: "space-between",
    // alignItems: "center",
  },
  delete: {
    flex: 1,
    alignSelf: "center",
    // backgroundColor: "yellow",
    paddingBottom: 10,
    paddingLeft: 10,
    marginLeft: 5,
    marginRight: -15,
  },
  text: {
    fontSize: 16,
    color: "#333",
  },
  detail: {
    backgroundColor: "#fff",
    elevation: 4, //设置阴影角度，通过这个设置有无阴影
    shadowOffset: {
      width: 0,
      height: 4,
    },
    shadowRadius: 4, // 设置阴影模糊半径
    shadowOpacity: 0.1, // 设置阴影的不透明度
    shadowColor: "gray", // 设置阴影色
    marginBottom: 20,
    marginLeft: 25,
    marginRight: 25,
    borderRadius: 10,
    padding: 10,
  },

  detailText: {
    fontSize: 15,
    color: "#333",
  },
  detailItem: {
    // flexDirection: "row",
    // justifyContent: "space-between",
    padding: 3,
    marginLeft: 10,
    marginRight: 5,
    alignContent: "center",
    flexDirection: "row",
  },
  editItem: {
    flexDirection: "row",
    justifyContent: "space-between",
    padding: 8,
    marginLeft: 10,
    marginRight: 5,
    alignItems: "center",
    // flexDirection: "row",
  },
  tag: {
    borderWidth: 1,
    borderColor: "#d1d1d6",

    paddingLeft: 10,
    paddingRight: 10,
    borderRadius: 10,
    color: "#d1d1d6",
    fontSize: 14,
  },
  selectedTag: {
    borderWidth: 1,
    borderColor: "#F9be7d",

    paddingLeft: 10,
    paddingRight: 10,
    borderRadius: 10,
    color: "#F9be7d",
  },
  inputView: {
    justifyContent: "center",
    width: "80%",
    borderColor: "#51bfe5",
    borderBottomWidth: 1,
    flexDirection: "row",
    alignItems: "center",
    paddingRight: 10,
  },
});

export default materialCard;
